import cv2
import numpy as np
import padocr
import operation
import time, math
import threading







def get_current_coordinate(device_serial = None):

    return padocr.get_current_position(device_serial=device_serial)



"""以下函数为移动到目的地坐标"""



# 根据当前坐标和目标坐标，判断是否到达目标
def reached_target(current_coord, target_coord, threshold=0):
    # 判断是否在目标坐标附近，允许一个误差范围 threshold
    return abs(current_coord[0] - target_coord[0]) <= threshold and abs(current_coord[1] - target_coord[1]) <= threshold


# 根据当前坐标和目标坐标，计算移动的方向
def calculate_direction(current_coord, target_coord):
    delta_x = target_coord[0] - current_coord[0]
    delta_y = target_coord[1] - current_coord[1]

    # Normalize the direction vector (dx, dy) to one of 8 directions

    angle = math.atan2(delta_y, delta_x) * 180 / math.pi  # Convert to degrees
    if -22.5 <= angle < 22.5:
        return 'right'
    elif 22.5 <= angle < 67.5:
        return 'down_right'
    elif 67.5 <= angle < 112.5:
        return 'down'
    elif 112.5 <= angle < 157.5:
        return 'down_left'
    elif 157.5 <= angle or angle < -157.5:
        return 'left'
    elif -157.5 <= angle < -112.5:

        return 'up_left'
    elif -112.5 <= angle < -67.5:
        return 'up'
    elif -67.5 <= angle < -22.5:
        return 'up_right'


target_coordinates = {
    'up': (544, 182),
    'down': (538, 495),
    'left': (350, 310),
    'right': (769, 303),
    'up_left': (382, 159),
    'up_right': (691, 173),
    'down_left': (388, 467),
    'down_right': (711, 435)
}

import os


def swipe(direction, duration=100):
    """ADB滑动函数
    :param direction: 8个方向之一 ['up', 'down', 'left', 'right', 'up_left', 'up_right', 'down_left', 'down_right']
    :param duration: 滑动持续时间(毫秒)
    """
    x0, y0 = 146, 751  # 中心点坐标
    distance = 150  # 滑动距离

    # 计算目标点坐标
    if direction == 'up':
        x1, y1 = x0, y0 - distance
    elif direction == 'down':
        x1, y1 = x0, y0 + distance
    elif direction == 'left':
        x1, y1 = x0 - distance, y0
    elif direction == 'right':
        x1, y1 = x0 + distance, y0
    elif direction == 'up_left':
        x1, y1 = x0 - distance * 0.707, y0 - distance * 0.707  # 0.707≈sin45°
    elif direction == 'up_right':
        x1, y1 = x0 + distance * 0.707, y0 - distance * 0.707
    elif direction == 'down_left':
        x1, y1 = x0 - distance * 0.707, y0 + distance * 0.707
    elif direction == 'down_right':
        x1, y1 = x0 + distance * 0.707, y0 + distance * 0.707
    else:
        raise ValueError("Invalid direction")

    # 执行ADB滑动命令
    os.system(f'adb shell input swipe {x0} {y0} {x1} {y1} {duration}')


def swipe_run(direction, duration=100):
    """ADB滑动函数
    :param direction: 8个方向之一 ['up', 'down', 'left', 'right', 'up_left', 'up_right', 'down_left', 'down_right']
    :param duration: 滑动持续时间(毫秒)
    """
    x0, y0 = 278, 612  # 中心点坐标
    distance = 150  # 滑动距离

    # 计算目标点坐标
    if direction == 'up':
        x1, y1 = x0, y0 - distance
    elif direction == 'down':
        x1, y1 = x0, y0 + distance
    elif direction == 'left':
        x1, y1 = x0 - distance, y0
    elif direction == 'right':
        x1, y1 = x0 + distance, y0
    elif direction == 'up_left':
        x1, y1 = x0 - distance * 0.707, y0 - distance * 0.707  # 0.707≈sin45°
    elif direction == 'up_right':
        x1, y1 = x0 + distance * 0.707, y0 - distance * 0.707
    elif direction == 'down_left':
        x1, y1 = x0 - distance * 0.707, y0 + distance * 0.707
    elif direction == 'down_right':
        x1, y1 = x0 + distance * 0.707, y0 + distance * 0.707
    else:
        raise ValueError("Invalid direction")

    # 执行ADB滑动命令
    os.system(f'adb shell input swipe {x0} {y0} {x1} {y1} {duration}')


# 示例使用
swipe('up')  # 向上滑动
swipe('right')  # 向右滑动
swipe('down_left')  # 向左下滑动
#
# def move_to_target( target_coord, region=(45, 778, 140, 20)):
#
#     try:
#         start_time = time.time()
#         while True:
#             end_time = time.time()
#             if end_time - start_time > 100:
#                 break
#             time.sleep(0.1)
#             # 获取当前坐标
#             current_coord = get_current_coordinate(region)
#
#
#
#             # 计算方向
#             direction = calculate_direction(current_coord, target_coord)
#             opration.move_mouse(target_coordinates[direction][0], target_coordinates[direction][1])
#
#             opration.send_right_mouse_down(target_coordinates[direction][0], target_coordinates[direction][1])
#
#             if reached_target(current_coord, target_coord):
#                 print(f"到达目标坐标: {target_coord}")
#                 opration.send_right_mouse_up(target_coordinates[direction][0], target_coordinates[direction][1])
#
#                 break  # 目标到达时停止移动
#
#
#             time.sleep(0.05)  # 等待一小段时间后再次检测坐标
#     finally:
#         pass

import queue
def move_to_target(target_coord, device_serial = None):

    start_time = time.time()
    while True:
        end_time = time.time()

        time.sleep(0.1)
        # 获取当前坐标
        current_coord = get_current_coordinate(device_serial=device_serial)

        if reached_target(current_coord, target_coord):
            print(f"到达目标坐标: {target_coord}")
            break  # 目标到达时停止移动
        # 计算方向
        direction = calculate_direction(current_coord, target_coord)
        swipe(direction)



        if end_time - start_time > 60:

            operation.go_home()
            break


        time.sleep(0.4)  # 等待一小段时间后再次检测坐标


# 示例调用
# start_coord = (1312, 287)
# target_coord = (538, 457)
# region = None  # 自定义坐标区域
# move_to_target(start_coord, target_coord, region)

# 示例使用
if __name__ == "__main__":
    # 获取窗口句柄
    client = operation.connect_emulator()
    devices = client.devices()

    if not devices:
        print("没有找到连接的设备")
        exit()

    # 打印所有设备信息
    print("可用设备:")
    for i, device in enumerate(devices):
        print(f"{i}: {device.serial}")
    selected_device = devices[0]
    # # 激活
    # time.sleep(1)

    move_to_target((338, 331), device_serial=selected_device.serial)

